package edu.hrbeu.crc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hrbeu.crc.constant.ErrorConstant;
import edu.hrbeu.crc.context.BaseContext;
import edu.hrbeu.crc.mapper.UserMapper;
import edu.hrbeu.crc.pojo.dto.UserDTO;
import edu.hrbeu.crc.pojo.dto.UserLoginDTO;
import edu.hrbeu.crc.pojo.entity.User;
import edu.hrbeu.crc.service.UserService;
import edu.hrbeu.crc.common.utils.AesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AesUtil aesUtil;
    // 默认头像
    private static final String ACQUIESCE_AVATAR = "http://keepbooks-crc.oss-cn-beijing.aliyuncs.com/images/2025-05-20/7147141b-9307-4345-87df-5ef3e12f26dc_1747745747551.png";

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 加密用户名和密码
        String encryptUsername = aesUtil.encrypt(userLoginDTO.getUsername());
        String encryptPassword = aesUtil.encrypt(userLoginDTO.getPassword());

        // 构造条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("username",encryptUsername)
                .eq("password",encryptPassword);
        User user = getOne(queryWrapper);
        if (user == null){
            return null;
        }
        // 确定登录，更新最后登录时间
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<User>()
                .set("LAST_LOGIN",LocalDateTime.now())
                .eq("id", user.getId());
        user.setLastLogin(LocalDateTime.now());
        update(null,updateWrapper);
        // 对user中的用户名和密码解密
        user.setUsername(aesUtil.decrypt(user.getUsername()));

        return user;
    }

    /**
     * 用户注册
     * @param user
     */
    @Override
    public String register(User user) {
        // 用户名是否重复
        if (usernameIsRepeated(user.getUsername())) return ErrorConstant.USERNAME_REPETITION;
        // 对用户名和密码加密存储
        String encryptUsername = aesUtil.encrypt(user.getUsername());
        user.setUsername(encryptUsername);
        user.setPassword(aesUtil.encrypt(user.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setAvatar(ACQUIESCE_AVATAR);// 默认头像
        super.save(user);
        return null;
    }

    // 检查用户名是否与数据库中存储数据重复
    private boolean usernameIsRepeated(String username) {
        String encryptUsername = aesUtil.encrypt(username);
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("username",encryptUsername);
        User selectUser = getOne(queryWrapper);
        // true：用户名重复
        return selectUser != null;
    }

    /**
     * 修改信息
     * @param userDTO
     */
    @Override
    public String updateMsg(UserDTO userDTO) {
        // 判断用户名是否重复
        String encryptUsername = aesUtil.encrypt(userDTO.getUsername());
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("username",encryptUsername);
        User selectUser = getOne(queryWrapper);
        if (!Objects.equals(selectUser.getId(), BaseContext.getCurrentId())) {
            return ErrorConstant.USERNAME_REPETITION;
        }
        // 将username加密存储
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .set(userDTO.getUsername() != null ,User::getUsername,encryptUsername)
                .set(userDTO.getAvatar() != null ,User::getAvatar,userDTO.getAvatar())
                .set(userDTO.getPhone() != null ,User::getPhone,userDTO.getPhone())
                .eq(User::getId, BaseContext.getCurrentId());
        update(wrapper);
        return null;
    }

    @Override
    public User getUser(Integer userId) {
        User user = getById(userId);
        // 解密
        user.setUsername(aesUtil.decrypt(user.getUsername()));
        return user;
    }


}
